import 'package:znmm/network/dio_https.dart';
import 'package:znmm/network/notify_listener.dart';

import '../model/currency_rate_model.dart';

class ToolBoxMag {
  static final ToolBoxMag _singleton = ToolBoxMag._internal();
  factory ToolBoxMag() {
    return _singleton;
  }

  ToolBoxMag._internal();

  void doSomething() {
    print("Doing something...");
  }

  // 获取汇率数据
  //List<Map<String, dynamic>> rateList = [];
  List<CurrencyRateModel> rateModelList = [];
  Future<void> fetchData() async {
    if (rateModelList.isNotEmpty) return;

    double exchangeRate = 0.0; // 汇率数据

    var response = await DioHttps().request(
      "https://v6.exchangerate-api.com/v6/fe875ec7b1e1138f89e02c92/latest/USD", // 请求的路径
      method: DioMethod.get, // 请求类型：GET
    );
    if (response == null) return;
    //print("response$response");
    //final data = jsonDecode(response.body);

    exchangeRate = response['conversion_rates']['CNY'];

    // 提取 conversion_rates
    var conversionRates = response['conversion_rates'];

    // 输出所有 key 和 value
    // conversionRates.forEach((key, value) {
    //   print('$key: $value');
    // });

    // 将转换率数据转换成 List
    rateModelList.clear();
    for (var entry in conversionRates.entries) {
      //rateList.add({'currency': entry.key, 'rate': entry.value});

      CurrencyRateModel pMol = CurrencyRateModel();
      pMol.currency = entry.key;
      pMol.rate = (entry.value is int)
          ? (entry.value as int).toDouble()
          : entry.value; // 确保 rate 是 double 类型
      pMol.country = currencyToCountry[entry.key] ?? "未知国家";

      rateModelList.add(pMol);
    }

    NotifyCenter().postNotification(NotifyKey.toolBoxKey, data: exchangeRate);

    // 处理响应数据
    print(response);
  }
}


  // Future<void> _fetchExchangeRate() async {
  //   try {
  //     final response = await http.get(Uri.parse(
  //         "https://v6.exchangerate-api.com/v6/fe875ec7b1e1138f89e02c92/latest/USD")); // 替换为真实 API KEY
  //     print("response$response");
  //     if (response.statusCode == 200) {
  //       final data = jsonDecode(response.body);
  //       setState(() {
  //         _exchangeRate = data['conversion_rates']['CNY'];
  //       });
  //     } else {
  //       throw Exception('Failed to load exchange rate');
  //     }
  //   } catch (e) {
  //     print('Error fetching exchange rate: $e');
  //   }
  // }